<template>
  <div class="menu-container">
    <div class="search-bar">
      <a-row :gutter="16">
        <a-col :span="6">
          <a-input-search
            v-model="searchKeyword"
            placeholder="请输入菜单名称"
            @search="handleSearch"
          />
        </a-col>
        <a-col :span="18" style="text-align: right">
          <a-button type="primary" @click="handleAdd">
            <template #icon><icon-plus /></template>
            新增菜单
          </a-button>
        </a-col>
      </a-row>
    </div>

    <a-table
      :data="menuList"
      :loading="loading"
      row-key="id"
      :pagination="false"
      :tree-props="{ children: 'children' }"
    >
      <template #columns>
        <a-table-column title="菜单名称" data-index="menuName" />
        <a-table-column title="图标" data-index="icon" align="center">
          <template #cell="{ record }">
            <i :class="record.icon" />
          </template>
        </a-table-column>
        <a-table-column title="排序" data-index="sort" align="center" />
        <a-table-column title="权限标识" data-index="permission" />
        <a-table-column title="路由地址" data-index="path" />
        <a-table-column title="组件路径" data-index="component" />
        <a-table-column title="菜单类型" data-index="menuType" align="center">
          <template #cell="{ record }">
            <a-tag :color="getMenuTypeColor(record.menuType)">
              {{ getMenuTypeText(record.menuType) }}
            </a-tag>
          </template>
        </a-table-column>
        <a-table-column title="状态" data-index="status" align="center">
          <template #cell="{ record }">
            <a-switch
              :model-value="record.status === 1"
              @change="(value) => handleStatusChange(record, value)"
            />
          </template>
        </a-table-column>
        <a-table-column title="创建时间" data-index="createTime">
          <template #cell="{ record }">
            {{ formatDate(record.createTime) }}
          </template>
        </a-table-column>
        <a-table-column title="操作" align="center" :width="200">
          <template #cell="{ record }">
            <a-space>
              <a-button type="text" @click="handleAdd(record)">
                新增
              </a-button>
              <a-button type="text" @click="handleEdit(record)">
                编辑
              </a-button>
              <a-popconfirm
                content="确认删除该菜单吗？"
                @ok="handleDelete(record)"
              >
                <a-button type="text" status="danger">
                  删除
                </a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </a-table-column>
      </template>
    </a-table>

    <!-- 菜单表单对话框 -->
    <a-modal
      v-model:visible="dialogVisible"
      :title="formTitle"
      @ok="handleSubmit"
      @cancel="handleCancel"
    >
      <a-form :model="menuForm" ref="menuFormRef" :style="{ width: '600px' }">
        <a-form-item field="parentId" label="上级菜单">
          <a-tree-select
            v-model="menuForm.parentId"
            :data="menuTree"
            :field-names="{ key: 'id', title: 'menuName' }"
            placeholder="请选择上级菜单"
            allow-clear
          />
        </a-form-item>
        <a-form-item field="menuType" label="菜单类型" :rules="[{ required: true, message: '请选择菜单类型' }]">
          <a-radio-group v-model="menuForm.menuType">
            <a-radio value="M">目录</a-radio>
            <a-radio value="C">菜单</a-radio>
            <a-radio value="F">按钮</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item field="menuName" label="菜单名称" :rules="[{ required: true, message: '请输入菜单名称' }]">
          <a-input v-model="menuForm.menuName" placeholder="请输入菜单名称" />
        </a-form-item>
        <a-form-item field="icon" label="菜单图标" v-if="menuForm.menuType !== 'F'">
          <a-input v-model="menuForm.icon" placeholder="请输入菜单图标" />
        </a-form-item>
        <a-form-item field="sort" label="显示排序">
          <a-input-number v-model="menuForm.sort" :min="0" />
        </a-form-item>
        <a-form-item field="path" label="路由地址" v-if="menuForm.menuType !== 'F'">
          <a-input v-model="menuForm.path" placeholder="请输入路由地址" />
        </a-form-item>
        <a-form-item field="component" label="组件路径" v-if="menuForm.menuType === 'C'">
          <a-input v-model="menuForm.component" placeholder="请输入组件路径" />
        </a-form-item>
        <a-form-item field="permission" label="权限标识" v-if="menuForm.menuType === 'F'">
          <a-input v-model="menuForm.permission" placeholder="请输入权限标识" />
        </a-form-item>
        <a-form-item field="isExternal" label="是否外链" v-if="menuForm.menuType !== 'F'">
          <a-switch v-model="menuForm.isExternal" />
        </a-form-item>
        <a-form-item field="isCache" label="是否缓存" v-if="menuForm.menuType === 'C'">
          <a-switch v-model="menuForm.isCache" />
        </a-form-item>
        <a-form-item field="isVisible" label="是否显示" v-if="menuForm.menuType !== 'F'">
          <a-switch v-model="menuForm.isVisible" />
        </a-form-item>
        <a-form-item field="status" label="菜单状态">
          <a-switch v-model="menuForm.status" :checked-value="1" :unchecked-value="0" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Message } from '@arco-design/web-vue'
import { IconPlus } from '@arco-design/web-vue/es/icon'
import request from '@/api/request'

// 数据列表
const menuList = ref([])
const menuTree = ref([])
const loading = ref(false)
const searchKeyword = ref('')

// 表单相关
const dialogVisible = ref(false)
const formTitle = ref('')
const menuForm = ref({
  id: null,
  parentId: null,
  menuName: '',
  menuType: 'C',
  icon: '',
  sort: 0,
  path: '',
  component: '',
  permission: '',
  isExternal: false,
  isCache: true,
  isVisible: true,
  status: 1
})
const menuFormRef = ref()

// 获取菜单列表
const getMenuList = async () => {
  menuList.value = []
  try {
    loading.value = true
    const res = await request.get('/api/SysMenu/list', {
      params: { keyword: searchKeyword.value }
    })
    menuList.value = res.data
    
  } catch (error) {
    Message.error('获取菜单列表失败')
  } finally {
    loading.value = false
    
    
  }
}

// 获取菜单树
const getMenuTree = async () => {
  try {
    const res = await request.get('/api/SysMenu/tree')
    menuTree.value = res.data
  } catch (error) {
    Message.error('获取菜单树失败')
  }
}

// 搜索
const handleSearch = () => {
  getMenuList()
}

// 新增菜单
const handleAdd = (record) => {
  formTitle.value = '新增菜单'
  menuForm.value = {
    id: null,
    parentId: record ? record.id : null,
    menuName: '',
    menuType: 'C',
    icon: '',
    sort: 0,
    path: '',
    component: '',
    permission: '',
    isExternal: false,
    isCache: true,
    isVisible: true,
    status: 1
  }
  getMenuTree()
  dialogVisible.value = true
}

// 编辑菜单
const handleEdit = (record) => {
  formTitle.value = '编辑菜单'
  menuForm.value = { ...record }
  getMenuTree()
  dialogVisible.value = true
}

// 提交表单
const handleSubmit = async () => {
  try {
    await menuFormRef.value.validate()
    const isEdit = menuForm.value.id !== null
    const api = isEdit
      ? `/api/SysMenu/${menuForm.value.id}`
      : '/api/SysMenu'
    const method = isEdit ? 'put' : 'post'
    
    const res = await request[method](api, menuForm.value)
    Message.success(res.message)
    dialogVisible.value = false
    getMenuList()
  } catch (error) {
    Message.error(error.message || '操作失败')
  }
}

// 取消表单
const handleCancel = () => {
  menuFormRef.value.resetFields()
  dialogVisible.value = false
}

// 删除菜单
const handleDelete = async (record) => {
  try {
    const res = await request.delete(`/api/SysMenu/${record.id}`)
    Message.success(res.message)
    getMenuList()
  } catch (error) {
    Message.error('删除失败')
  }
}

// 修改状态
const handleStatusChange = async (record, value) => {
  try {
    const status = value ? 1 : 0
    const res = await request.put(`/api/SysMenu/${record.id}/status/${status}`)
    Message.success(res.message)
    getMenuList()
  } catch (error) {
    Message.error('修改状态失败')
  }
}

// 获取菜单类型文本
const getMenuTypeText = (type) => {
  const types = {
    'M': '目录',
    'C': '菜单',
    'F': '按钮'
  }
  return types[type] || '未知'
}

// 获取菜单类型颜色
const getMenuTypeColor = (type) => {
  const colors = {
    'M': 'blue',
    'C': 'green',
    'F': 'orange'
  }
  return colors[type] || 'gray'
}

// 格式化日期
const formatDate = (date) => {
  return new Date(date).toLocaleString()
}

onMounted(() => {
  getMenuList()
})
</script>

<style scoped>
.menu-container {
  padding: 16px;
}

.search-bar {
  margin-bottom: 16px;
}
</style>